﻿using Admin2024.Domain.Entity.System;
using Admin2024.Domain.IDomainService.System.IPermissionService;
using Admin2024.Domain.Interface;
using Admin2024.Domain.ObjValue;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Admin2024.Domain.DomainService.System.PermissionService
{
    public class ResourceManagementService : IResourceManagementService
    {
        private readonly IRepository<AppResource> ResourceRep;

        public ResourceManagementService(IRepository<AppResource> ResourceRep)
        {
            this.ResourceRep = ResourceRep;
        }
        public async Task<DomainResult<AppResource>> CreateResource(AppResource appResource)
        {
            var user = ResourceRep.Table.FirstOrDefault(w => w.ResourceName == appResource.ResourceName);

            if (user != null)
            {
                return DomainResult<AppResource>.Error("资源权限已存在");
            }
            var operation = await ResourceRep.CreateAsync(appResource);

            return DomainResult<AppResource>.Success(operation);
        }

        public async Task<DomainResult<AppResource>> DeleteResource(Guid resId)
        {
            var permission = await ResourceRep.DeleteAsync(resId);
            if (permission == null)
            {
                return DomainResult<AppResource>.Error("资源权限不存在");
            }
            return DomainResult<AppResource>.Success(permission);
        }

        public async Task<DomainResult<List<AppResource>>> GetResourceWithPagination(int page, int pageSize)
        {
            var ResourceList = await ResourceRep.GetListAsync();

            if (ResourceList.Count == 0)
            {
                return DomainResult<List<AppResource>>.Error("当前还没有任何用户");
            }
            var ResourceListPage = ResourceList.Skip((page - 1) * pageSize).Take(pageSize).Where(item => item.IsDeleted == false).ToList();

            return DomainResult<List<AppResource>>.Success(ResourceListPage);
        }

        public async   Task<DomainResult<AppResource>> GetAppResourceById(Guid id)
        {
            var permission = await ResourceRep.GetByIdAsync(id);
            if (permission == null)
            {
                return DomainResult<AppResource>.Error("资源权限不存在");
            }
            return DomainResult<AppResource>.Success(permission);
        }

        public async Task<DomainResult<AppResource>> UpdateResourceProfile(Guid Id, AppResource entity)
        {
            var resource = await ResourceRep.GetByIdAsync(Id);
            if (resource == null)
            {
                return DomainResult<AppResource>.Error("操作权限不存在");
            }

            resource.ResourceName = entity.ResourceName;
            resource.Url = entity.Url;

            await ResourceRep.UpdateAsync(resource);

            return DomainResult<AppResource>.Success(resource);
        }
    }
}
